package cn.work100.modular.system.controller;

import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import cn.work100.core.common.constant.state.ManagerStatus;
import cn.work100.core.common.exception.BizExceptionEnum;
import cn.work100.core.shiro.ShiroKit;
import cn.work100.modular.system.entity.User;
import cn.work100.modular.system.model.UserDto;
import cn.work100.modular.system.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Date;

@Controller
@RequestMapping("/openApi")
public class OpenApiController extends BaseController {

    @Resource
    private UserService userService;

    /**
     * 注册跳转
     * */
    @RequestMapping("/reg")
    public String reg(){
        return "/register.html";
    }
    /**
     * 用户注册
     * */
    @RequestMapping("/register")
    @ResponseBody
    public ResponseData register(@Valid User user, BindingResult result){
        if (result.hasErrors()) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        User theUser = userService.getByAccount(user.getAccount());
        if (theUser != null) {
            throw new ServiceException(BizExceptionEnum.USER_ALREADY_REG);
        }
        String salt = ShiroKit.getRandomSalt(5);
        String password = ShiroKit.md5(user.getPassword(), salt);
        user.setCreateTime(new Date());
        user.setStatus(ManagerStatus.OK.getCode());
        user.setPassword(password);
        user.setSalt(salt);
        user.setMoney(0.00);
        user.setDeptId((long)25);
        user.setRoleId("5");
        user.setPhone("未设置");
        user.setBirthday(new Date());
        user.setName("work100-匿名用户");
        user.setCreateUser((long)1);
        userService.addsave(user);
        return ResponseData.success();
    }
}
